import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
    // ...
    state: {
        goodList: [],
    },
    mutations: {
        setGoodsList(state, newList) {
            state.goodList = newList
        },
        btn(state, payload) {
            state.goodList.forEach(ele => {
                ele.goods_state = payload
            })
        }
    },
    actions: {
        // 发送axios
        async asyncSetGoodsList(store) {
            const resp = await axios({
                url: 'https://www.escook.cn/api/cart'
            })
            // 异步的操作发送给同步操作 commit调用
            store.commit('setGoodsList', resp.data.list)
        },


    },
    getters: {
        cartlist(state) {
            return state.goodList
        },
        isAll(state) {
            return state.goodList.every(ele => {
                return ele.goods_state == true
            })
        },
        total(state) {
            return state.goodList.reduce((h, n) => {
                if (n.goods_state) {
                    h += n.goods_count * n.goods_price
                }
                return h
            }, 0)
        },
        totallength(state) {
            return state.goodList.reduce((h, n) => {
                if (n.goods_state) {
                    h += n.goods_count
                }
                return h
            }, 0)
        }
    }
})

export default store